package pe.com.hermes.hermetic.web.controller.general;

import pe.com.hermes.hermetic.beans.MatrizBean;
import pe.com.hermes.hermetic.negocio.service.HermeticFacade;

import pe.com.hermes.hermetic.negocio.ultil.Util;
import pe.com.hermes.hermetic.web.controller.base.IController;

import pe.com.hermes.hermetic.web.forms.SelecCuentaForm;
import pe.com.hermes.hermetic.web.forms.SelecPuntoForm;
import pe.com.hermes.hermetic.web.forms.SelecUnidMoneForm;
import pe.com.hermes.hermetic.web.forms.SelectMatrizForm;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;


import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/seleccionarMatriz.html")
@SessionAttributes(value={"form"})
public class SeleccionarMatrizController implements IController{
    protected final static Logger logger = Logger.getLogger(SeleccionarMatrizController.class);
    protected final static String TODOS = "0";
    protected final static String ALGUNOS = "1";
    @Autowired
    private HermeticFacade servicioHermetic;
    @RequestMapping(method={RequestMethod.GET})    
    protected String showForm(ModelMap model,HttpServletRequest request)throws Exception{
        try {
            logger.info(this.getClass().toString()+" "+"metodo: GET");
            SelectMatrizForm form = new SelectMatrizForm();
            form.setCliente((String)request.getSession(false).getAttribute("cliente"));
            form.setCodSucuHtb((String)request.getSession(false).getAttribute("sucursal"));
            List listSucursales = servicioHermetic.getSucursalesNoTodos();
            List listMatrices = new ArrayList();        
            listMatrices = servicioHermetic.getListMatrices(form.getCliente(),form.getCodSucuHtb(),"");
            String[] chksMatriz = (String[])request.getSession(false).getAttribute("chks");
            listMatrices = Util.setChksSession(chksMatriz, listMatrices);
            form.setListMatrices(listMatrices);            
            request.getSession(false).setAttribute("listMatrices",listMatrices);
            model.put("listSucursales",listSucursales);
            model.put("listMatrices",listMatrices);
            model.put(FORM_KEY,form);
            return FORM_SELECT_MATRIZ;
        }
        catch (Exception e) {
            return FORM_ERROR_POPUP_VIEW;
        }
    }
    @RequestMapping(params={"accion=buscarMatrizBySucursal","codSucuHtb","desMat"}) 
    protected String buscarMatrizBySucursal(@RequestParam("codSucuHtb") String codSucuHtb,@RequestParam("desMat") String desMat ,ModelMap model,HttpServletRequest request)throws Exception{
        logger.info(this.getClass().toString()+" "+"metodo: GET");
        SelectMatrizForm form = new SelectMatrizForm();
        form.setCliente((String)request.getSession(false).getAttribute("cliente"));        
        List listSucursales = servicioHermetic.getSucursalesNoTodos();
        List listMatrices = new ArrayList();        
        listMatrices = servicioHermetic.getListMatrices(form.getCliente(),codSucuHtb,desMat);
        String[] chksMatriz = (String[])request.getSession(false).getAttribute("chks");
        listMatrices = Util.setChksSession(chksMatriz, listMatrices);
        form.setListMatrices(listMatrices);        
        if(desMat.equals(""))
            request.getSession(false).setAttribute("listMatrices",listMatrices);
        model.put("listSucursales",listSucursales);
        model.put("listMatrices",listMatrices);
        model.put(FORM_KEY,form);
        return FORM_SELECT_MATRIZ;
    }
    
    @RequestMapping(params={"accion=searchDesMat"}) 
    protected @ResponseBody String[] searchDesMat(HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: searchDesMat");        
        List listMatrices = (List)request.getSession(false).getAttribute("listMatrices");
        String[] arrayMatriz = new String[listMatrices.size()];
        for(int i=0;i<listMatrices.size();i++){
            arrayMatriz[i] = ((MatrizBean)listMatrices.get(i)).getDesMat();
        }
        return arrayMatriz;
    }
    @RequestMapping(params={"accion=selectCodMat","codMat"}) 
    protected @ResponseBody String[] selectCodMat(@RequestParam("codMat") String codMat,@ModelAttribute(FORM_KEY) SelectMatrizForm form,HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: selectCodMat");        
        String[] chks = (String[])request.getSession(false).getAttribute("chks");
        if(("").equals(codMat))
            return chks; 
        if(chks!=null)
            for(int i=0;i<chks.length;i++){                
                if(chks[i]!=null&&chks[i].equals(codMat)){
                    break;
                }
                if(chks[i]==null){
                    chks[i] = codMat;
                    break;
                }
            }            
        else{
            chks= new String[1000];
            chks[0]=codMat;
        }        
        request.getSession(false).setAttribute("chks",chks);        
        return chks;
    }
    @RequestMapping(params={"accion=deSssselectCodMat","codMat"}) 
    protected @ResponseBody String[] deSssselectCodMat(@RequestParam("codMat") String codMat,@ModelAttribute(FORM_KEY) SelectMatrizForm form,HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: deselectCodCuenta");        
        String[] chksModulo = (String[])request.getSession(false).getAttribute("chks");

        if(chksModulo!=null && chksModulo.length > 0)
            for(int i=0;i<chksModulo.length;i++){                
                if(chksModulo[i]!=null && chksModulo[i].equals(codMat)){
                    chksModulo[i] = null;
                    break;
                }
            }            
        
        request.getSession(false).setAttribute("chks",chksModulo);        
        return chksModulo;
    }
    @RequestMapping(params={"accion=selectTodos","codTodos"}) 
    protected String selectTodos(@RequestParam("codTodos") boolean codTodos ,ModelMap model,HttpServletRequest request)throws Exception{
        logger.info(this.getClass().toString()+" "+"metodo: GET");
        SelectMatrizForm form = (SelectMatrizForm)model.get("form");//new SelecCuentaForm();
        
        //Asigno el check a todos los elenmentos de la lista Cuenta        
        List listMatrices = form.getListMatrices(); 
        listMatrices = Util.setChksTodos(codTodos, listMatrices);        
        form.setListMatrices(listMatrices);
        
        //Subo a session los todos los Checks Cuenta
        if (codTodos) {
            String[] chksMatrices = Util.listToStringArray(listMatrices);
            request.getSession(false).setAttribute("chks",chksMatrices);       
        }else {
            request.getSession(false).setAttribute("chks",null);        
        }
        
        request.getSession(false).setAttribute("listMatrices",listMatrices);
        model.put("listMatrices",listMatrices);
        model.put(FORM_KEY,form);
        return FORM_SELECT_MATRIZ;
    }
    @RequestMapping(params={"accion=hasMatrices","codMatriz"}) 
    protected @ResponseBody boolean hasMatrices(@RequestParam("codMatriz") String codMatriz,HttpServletRequest request)throws Exception{        
        logger.info(this.getClass().toString()+" "+"metodo: hasMatrices");        
        String[] chksMatrices = (String[])request.getSession(false).getAttribute("chks");
        String cliente = (String)request.getSession(false).getAttribute("cliente");
        String sucursal = (String)request.getSession(false).getAttribute("sucursal");
        boolean existeMatriz = servicioHermetic.getIsMatrizActive(cliente,sucursal);
        if(!existeMatriz)
            return true;
        boolean hasCuentas = false;
        if((TODOS).equals(codMatriz))
            hasCuentas =  true;        
        if((ALGUNOS).equals(codMatriz)&&Util.contDatosSession(chksMatrices)>0)
            hasCuentas =  true;
        return hasCuentas;
    } 
}
